<!--
*@Author: QWP
*@Description: 合同
*@Params: pType   1 收入合同      2 支出合同       3 合同查询
*@Date 2024-07-15 09:58
-->
<template>
  <a-layout class="f-h-100 s-bg-white" id="test">
    <u-search-header>
      <u-form
        :model="searchF.model"
        :gutter="16"
        :elements="searchEl"
        class="f-w-auto"
        :isSearch="true"
        @formChange="getSearch(1)">
        <a-col>
          <a-space>
            <u-icon-button @click="getSearch(1)">查询</u-icon-button>
            <!-- <u-icon-button itype="export" @click="">导出</u-icon-button> -->
          </a-space>
        </a-col>
        <a-col flex="1" v-if="route.params.pType != 3">
          <a-row justify="end">
            <a-space>
              <u-icon-button itype="add" @click="toEdit(1)">新增</u-icon-button>
              <u-icon-button itype="edit" @click="toEdit(2)">修改</u-icon-button>
              <u-icon-button itype="delete" @click="deleteBtn">删除 </u-icon-button>
            </a-space>
          </a-row>
        </a-col>
      </u-form>
    </u-search-header>
    <u-table-content class="f-padding-rl24">
      <u-table
        :columns="columns"
        :data="tabData"
        v-model:pagination="pagenation"
        :loading="loading"
        :scroll="{ y: useTableScroll() }"
        @onDblclick="(record) => {
          keyid = record.keyid;
          showEdit = true;
        }"
        @onSelect="({ selectedRows }) => tabSelData = selectedRows" 
        @change="getSearch"></u-table>
    </u-table-content>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit v-model:open="showEdit"
    wrap-class-name="full-modal"
    :title="dialogTitle" 
    :keyid="keyid"
    @success="keyid = '', showEdit = false, getSearch()"
    @close="keyid = ''"/>

</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h, watch, } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate, onBeforeRouteLeave} from "vue-router";
import { _IFormEl } from "@/components/common/form/interface";
import { ColProps, FormItemProps, TableColumnProps } from "ant-design-vue";
import { CheckCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { numberC, messageC, alertC, nullC } from '@/util/common'
import { formatAmt, } from '@/util/format.ts'
import dayjs from "dayjs";
import Edit from './Edit.vue'
import { cloneDeep } from 'lodash'
import { useTableScroll } from '@/hooks/useTable'
import * as contractApi from '@/service/administration/contract'

const route = useRoute();
const router = useRouter();

onMounted(() => {
  getSearch();
})

const busiLabels = { 1: '收入', 2: '支出' }

let pagenation = reactive({
  total: 0,
  current: 1,
  pageSize: 50,
  showTotal: total => `共 ${total} 条`
})
const searchF = reactive({
  model: {
    contracttype: route.params.pType == 3 ? '' : computed(() => route.params.pType)
  },
});
const formItemProps: FormItemProps = reactive({
  labelWidth: computed(() => route.params.pType == 3 ? '72px' : '60px'),
  wrapperCol: { span: 24 },
});
const searchEl: Array<_IFormEl> = [
  // { label: "签订开始时间", key: "qdksrq", element: "datepicker", col: { span: 4 }, formItemProps: formItemProps,},
  // { label: "签订结束时间", key: "qdjsrq", element: "datepicker", col: { span: 4 }, formItemProps: formItemProps,},
  // { label: "合同状态", key: "htzt", element: "select", col: { span: 4 }, 
  //   formItemProps: formItemProps,
  //   componentProps: { 
  //     allowClear: true,
  //     options: [
  //       {label: '有效合同', value: '1'},
  //       {label: '无效合同', value: '2'},
  //       {label: '解除合同', value: '3'},
  //       {label: '终止合同', value: '4'},
  //       {label: '暂停合同', value: '5'},
  //     ] 
  //   },
  // },
  ...(route.params.pType == 3 ? [
    { label: "合同类型", key: "contracttype", element: "select", col: { span: 4 }, 
      formItemProps: formItemProps,
      componentProps: { 
        options: [
          {label: '收入合同', value: '1'},
          {label: '支出合同', value: '2'},
        ] 
      },
    }
  ] : []),
  { label: "关键字", key: "keywords", element: "input", col: { span: 4 }, formItemProps: formItemProps, 
    componentProps: { placeholder: '合同编号/名称' }
  },
];

// 列表
const loading = ref<boolean>(false)
const tabSelData = ref<any[]>([]);
const tabData = ref<any[]>([]);
let columns: Array<TableColumnProps> = reactive([
  { dataIndex: "index", title: "序号", width: 50, align: 'center',
    customRender: ({ index }) => index += 1
  },
  { dataIndex: "contractcode", title: "合同编号", width: 150,},
  { dataIndex: "contractname", title: "合同名称", width: 150, },
  ...( route.params.pType == 3 ? [
    { dataIndex: "contracttype", title: "合同类型", width: 100, align: 'center',
      customRender: ({ text }) => {
        return text ? `${nullC(busiLabels[text])}合同` : ''
      }
    },
  ] : []),
  { dataIndex: "contractdate", title: "签定时间", width: 100, align: 'center',
    customRender: ({ text }) => (text || '').split(' ')[0]
  },
  { dataIndex: "aname", title: "甲方名称", width: 150 },
  { dataIndex: "bname", title: "乙方名称", width: 150 },
  { dataIndex: "contractamount", title: "合同金额(元)", width: 150, align: 'right' ,
    customRender: ({ text }) => {
      return formatAmt(numberC(text))
    }
  },
  { dataIndex: "remark", title: "备注", width: 200 },
]);


// 获取列表数据
const getSearch = async (current?: number) => {
  if(current == 1) {
    pagenation.current = 1
  }
  loading.value = true;
  try {
    searchF.size = pagenation.pageSize;
    searchF.current = pagenation.current;
    
    const res = await contractApi.page(searchF)
    if(res.code == 0) {
      tabData.value = res.data.records;
      pagenation.total = res.data.total;
    }
  } catch (error) {}
  loading.value = false;
}

// 编辑
// let dialogTitle = ref<string>("合同编辑")
let dialogTitle = computed(() => {
  return nullC(busiLabels[route.params.pType]) + '合同编辑'
})
let showEdit = ref<boolean>(false)
let keyid = ref<string>('')
const toEdit = (type?: number) => {
  if(type == 2) {
    if(tabSelData.value.length != 1) {
      messageC("能且只能选择一条数据进行修改！");
      return
    }
    keyid.value = tabSelData.value[0]['keyid']
  } 
  showEdit.value = true
}

// 删除
const deleteBtn = async() => {
  if(tabSelData.value.length == 0) {
    messageC("请先选择需要删除的数据！");
    return
  }

  loading.value = true;
  try {
    await alertC("确认删除选中的数据?", "confirm")
    
    let ids = tabSelData.value.map((item) => item.keyid);
    
    const res = await contractApi.del({ ids: ids.join(",") });
    if(res.code == 0) {
      getSearch()
    }
    messageC(res.msg, res.code == 0 ? 'success' : 'error')
  } catch (error) {}
  loading.value = false;
}


</script>

<style lang="scss" scoped>
.icons-list :deep(.anticon) {
  margin-right: 6px;
  font-size: 24px;
}
</style>
